package com.kifas.controller;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.kifas.entity.SalesEntity;
import com.kifas.model.xml.PersistStatus;
import com.kifas.model.xml.SalesModel;
import com.kifas.service.EntityServiceManager;

@Component
@Scope("prototype")
@Path("/Sales")
public class SalesController {
	
	private static Logger log = Logger.getLogger(SalesController.class);

	@Context
	UriInfo uriInfo;
	
	@Autowired
	private EntityServiceManager entityManager;
	
	@GET
	@Produces(MediaType.TEXT_XML)
	public List<SalesModel> getSales() {
		List<SalesEntity> listSalesEntity = entityManager.getSales();
		List<SalesModel> sales = new ArrayList<SalesModel>();
		for (SalesEntity salesEntity : listSalesEntity) {
			SalesModel model = new SalesModel(salesEntity.getIdSales(), salesEntity.getNama(), salesEntity.getType(), salesEntity.getCreatedBy());
			sales.add(model);
		}
		return sales;
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public PersistStatus persist(JAXBElement<SalesModel> xml) {
		SalesModel model = xml.getValue();
		SalesEntity sales = new SalesEntity(null, model.getNama(), model.getType(), model.getNotelp(), model.getAlamat(), model.getEmail());
		try {
			entityManager.persist(sales);
		} catch (Exception e) {
			log.error("can not persist sales", e);
			return new PersistStatus("SalesEntity", "failed", "can not persist sales");
		}
		return new PersistStatus("SalesEntity", "success");
	}
	
	@PUT
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public PersistStatus update(JAXBElement<SalesModel> xml) {
		SalesModel model = xml.getValue();
		SalesEntity sales = new SalesEntity(model.getIdSales(), model.getNama(), model.getType(), model.getCreatedBy());
		try {
			entityManager.update(sales);
		} catch (Exception e) {
			log.error("can not update sales", e);
			return new PersistStatus("SalesEntity", "failed", "can not update sales");
		}
		return new PersistStatus("SalesEntity", "success");
	}

}
